package com.icebergteam.warfacewidget.ui;

import java.net.URI;
import java.util.LinkedHashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.json.JSONObject;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import com.icebergteam.warfacewidget.R;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.connection.NetworkManager;
import com.icebergteam.warfacewidget.news.ui.NewsPage;

public class TwitchTVVideoPlayerActivity {
	static final public String className = TwitchTVVideoPlayerActivity.class.getCanonicalName();
	public static final String MASK_JSON_FEED = "https://api.twitch.tv/kraken/channels/%s/videos?limit=10";
	public static final String PATTERN_URL = "twitch.tv";
	
	
	public TwitchTVVideoPlayerActivity () {
		
	}
	
	public static boolean initByUrl(final String url, final Context ctx){
		try{	
		
			String twitchTVUrl = TwitchTVVideoPlayerActivity.getTwitchTVUrl(url);
    	  	
	    	if(twitchTVUrl != null){
			
				NewsPage.errorDialog(String.format("%s - %s" , ctx.getString(R.string.news_page_failed_twitchtv), url),  ctx.getString(android.R.string.ok),  null, ctx.getString(R.string.news_page_open_with_twitchtv), new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent("android.intent.action.VIEW");
						intent.setData(Uri.parse(url));
						ctx.startActivity(intent);
					}
				}, ctx);
				return true;
	    	}
	    	return false;
		}
		catch(Exception e){
			LogManager.LogE(TwitchTVVideoPlayerActivity.className, LogManager.getExecuteMethodName(),e.getLocalizedMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public static String getTwitchTVUrl(String url){
		if(url.contains(PATTERN_URL)){
			return url;
		}
		return null;
	}
	
	
	public static String getTwitchTVUrl(Element object){
		String url ;
		if((url = getTwitchTVUrlObjectParam(object))!= null){
			return (url);
		}
			
		return null;
	}
	
	
	private static String getTwitchTVUrlObjectParam(Element object){
		Elements paramsData = object.select("[name = data]");
		String urlVideo = (paramsData.first()== null)?null:(paramsData.first().attr("value"));
		
		LogManager.LogVA(className, urlVideo);
		return getTwitchTVUrl(urlVideo);
	}
	
	public  static LinkedHashMap<String, String> decodeUrlParameters(String s)	 {
		 LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
		 try {
			List<NameValuePair> paramsList =  URLEncodedUtils.parse(new URI(s), "UTF-8");
			for(NameValuePair pair: paramsList){
				 params.put(pair.getName(), pair.getValue());
			}
		 }catch(Exception e) {
			 e.printStackTrace();
		 }
		 return params;
	 }
	
	public static JSONObject getTwitchTVVideoInfo(String channelName){
		try {
			return NetworkManager.getJSON(String.format(MASK_JSON_FEED, channelName));
		} catch (Exception e) {
			LogManager.LogEA(className, channelName, "bug", String.format(MASK_JSON_FEED, channelName), e.getLocalizedMessage());
			e.printStackTrace();
			return null;
		}
	}
	
	public static String getTwitchTVVideoThumbnailByChannelName(String channelName){
		try {
			JSONObject jsonObject = TwitchTVVideoPlayerActivity.getTwitchTVVideoInfo(channelName);
			return jsonObject.getJSONArray("videos").getJSONObject(0).getString("preview");
		} catch (Exception e) {
			LogManager.LogEA(className, channelName, "bug", e.getLocalizedMessage());
			e.printStackTrace();
			return null;
		}
	}
	
	public static String getTwitchTVVideoThumbnailByUrl(String url){
		try {
			String twitchTVUrl = TwitchTVVideoPlayerActivity.getTwitchTVUrl(url);
			String channelName =  decodeUrlParameters(twitchTVUrl).get("channel");
			
			return getTwitchTVVideoThumbnailByChannelName(channelName);
		} catch (Exception e) {
			LogManager.LogEA(className, url, "bug", e.getLocalizedMessage());
			e.printStackTrace();
			return null;
		}
	}
	
}
